"""
公共数据库连接模块
供所有插件使用，只负责连接池管理，不包含业务逻辑
"""
from typing import Optional, TYPE_CHECKING
import os

if TYPE_CHECKING:
    import aiomysql
else:
    try:
        import aiomysql
    except ImportError as e:
        aiomysql = None
        import sys
        print(f"[ERROR] aiomysql未安装")
        print(f"[DEBUG] Python路径: {sys.executable}")
        print(f"[DEBUG] Python版本: {sys.version}")
        print(f"[DEBUG] 导入错误详情: {e}")
        print(f"[DEBUG] 请确保在正确的环境中安装: pip install aiomysql")

# 数据库配置（可以从环境变量或配置文件读取）
DB_CONFIG = {
    "host": os.getenv("DB_HOST", "localhost"),
    "port": int(os.getenv("DB_PORT", 3306)),
    "user": os.getenv("DB_USER", "root"),
    "password": os.getenv("DB_PASSWORD", "123456"),
    "db": os.getenv("DB_NAME", "xiaoyibot"),
    "charset": "utf8mb4"
}

_pool = None


async def get_db_pool():
    """获取数据库连接池（单例模式）"""
    if aiomysql is None:
        raise ImportError("aiomysql未安装，请运行: pip install aiomysql")
    
    global _pool
    if _pool is None:
        _pool = await aiomysql.create_pool(
            host=DB_CONFIG["host"],
            port=DB_CONFIG["port"],
            user=DB_CONFIG["user"],
            password=DB_CONFIG["password"],
            db=DB_CONFIG["db"],
            charset=DB_CONFIG["charset"],
            autocommit=True,
            minsize=1,
            maxsize=10
        )
    return _pool


async def close_db_pool():
    """关闭数据库连接池"""
    global _pool
    if _pool is not None:
        _pool.close()
        await _pool.wait_closed()
        _pool = None

